﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NhJump.Persistence.Context;
using NhJump.Persistence.Tests.SqlServerIntegrationTests.Model;

namespace NhJump.Persistence.Tests.SqlServerIntegrationTests
{
    public abstract class SqlServerIntegrationFixtureBase
    {
        protected ISessionFactory Factory { get; private set; }

        protected SqlServerIntegrationFixtureBase()
        {
            var cfg = new Configuration();
            cfg.Properties[NHibernate.Cfg.Environment.ConnectionStringName] = "IntegrationTests";
            cfg.Properties[NHibernate.Cfg.Environment.ConnectionProvider] = "NHibernate.Connection.DriverConnectionProvider";
            cfg.Properties[NHibernate.Cfg.Environment.ConnectionDriver] = typeof(NHibernate.Driver.SqlClientDriver).AssemblyQualifiedName;
            cfg.Properties[NHibernate.Cfg.Environment.Dialect] = typeof(NHibernate.Dialect.MsSql2000Dialect).AssemblyQualifiedName;
            cfg.Properties[NHibernate.Cfg.Environment.ProxyFactoryFactoryClass] = "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";
            cfg.Properties[NHibernate.Cfg.Environment.GenerateStatistics] = "true";
            if (PersistentTypes != null)
            {
                foreach (var persistentType in PersistentTypes)
                {
                    cfg.AddClass(persistentType);
                }
            }

            new SchemaExport(cfg).Create(false, true);
            
            Factory = cfg.BuildSessionFactory();
        }

        private static IEnumerable<Type> PersistentTypes
        {
            get
            {
                string nsName = typeof (IntKeyedTestEntity).Namespace;

                return System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                    .Where(t => t.Namespace != null && t.Namespace.StartsWith(nsName));
            }
        }
    }
}
